<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\admin\model\Staff;
use app\admin\model\Msglog;
use app\admin\model\Company;
use app\admin\model\Salary;
use think\facade\Encrypt;

use app\common\service\AliSmsService;
use app\common\service\TxEss;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        if ($this->request->isPost()) {
            $name = input('name');
            $idcard = input('idcard');
            $mobile = input('mobile');
            $code = input('code');

            if (empty($name)) {
                $this->no('请输入用户名');
            }

            if (empty($idcard)) {
                $this->no('请输入身份证号');
            }

            if (empty($mobile)) {
                $this->no('请输入手机号');
            }

            if (empty($code)) {
                $this->no('请输入验证码');
            }

            $mobile_code = session('mobile_code');
            if (empty($mobile_code)) {
                $this->no('请先获取验证码');
            }

            if ($mobile_code['mobile'] != $mobile) {
                $this->no('手机号错误');
            }

            if ($mobile_code['code'] != $code) {
                $this->no('验证码错误');
            }

            // $staffInfo = Staff::where(['name'=>$name, 'idcard'=>$idcard, 'mobile'=>$mobile])->find();
            // if (empty($staffInfo)) {
            //     $this->no('通过姓名、身份证号、手机号未查到您的员工数据，请检查数据是否准确！');
            // }

            $staffInfo = Salary::where(['name'=>$name, 'idcard'=>$idcard, 'mobile'=>$mobile])->find();
            if (empty($staffInfo)) {
                $this->no('通过姓名、身份证号、手机号未查询到您的薪资数据，请检查数据是否准确！');
            }

            $username = $this->encrypt($name);
            $useridcard = $this->encrypt($idcard);
            $mobile = $this->encrypt($mobile);

            cookie('username', $username, 3600);
            cookie('useridcard', $useridcard, 3600);
            cookie('mobile', $mobile, 3600);

            $this->yes('success');
        }

        return $this->view->fetch();
    }

    public function salary()
    {
        $username = cookie('username');
        $useridcard = cookie('useridcard');
        $mobile = cookie('mobile');

        if (empty($username)) {
            header('location:' . url('index/index'));
            exit();
        }

        if (empty($useridcard)) {
            header('location:' . url('index/index'));
            exit();
        }

        if (empty($mobile)) {
            header('location:' . url('index/index'));
            exit();
        }

        $name = $this->decrypt($username);
        $idcard = $this->decrypt($useridcard);
        $mobile = $this->decrypt($mobile);

        // 查询工资数据
        $salaryList = Salary::where(['name'=>$name, 'idcard'=>$idcard, 'mobile'=>$mobile])->select();
        if (empty($salaryList)) {
            $this->no('用户薪资数据不存在');
        }

        $this->view->assign('salaryList', $salaryList);
        return $this->view->fetch();
    }

    // 注册
    public function register()
    {

        if ($this->request->isPost()) {
            $mobile = input('mobile');
            $code = input('code');

            if (empty($mobile)) {
                $this->no('请输入手机号');
            }

            if (empty($code)) {
                $this->no('请输入验证码');
            }

            $mobile_code = session('mobile_code');
            if (empty($mobile_code)) {
                $this->no('请先获取验证码');
            }

            if ($mobile_code['mobile'] != $mobile) {
                $this->no('手机号错误');
            }

            if ($mobile_code['code'] != $code) {
                $this->no('验证码错误');
            }

            $staffInfo = Staff::where('mobile', $mobile)->find();
            if (empty($staffInfo)) {
                $insertData = [
                    'mobile'=>$mobile,
                ];
                $res = Staff::create($insertData);
                if (!$res) {
                    $this->no('添加失败');
                }
                $uid = $res->id;
                $idcard = '';
            } else {
                $idcard = $staffInfo['idcard'];
                $uid = $staffInfo['id'];
            }

            session('salary_uid', $uid);
            $this->yes('success', ['idcard'=>$idcard]);
        }

        return $this->view->fetch();
    }

    // 修改用户信息
    public function saveuserinfo()
    {
        $uid = session('salary_uid');
        if (empty($uid)) {
            header('location:' . url('index/index'));
            exit();
        }

        $staffInfo = Staff::where('id', $uid)->find();
        if (empty($staffInfo)) {
            header('location:' . url('index/register'));
            exit();
        }


        if ($this->request->isPost()) {
            $name = input('name');
            $idcard = input('idcard');
            $permanentAddress = input('permanentAddress');
            $currentAddress = input('currentAddress');
            $gender = input('gender/d', 0);
            $urgent_name = input('urgent_name');
            $urgent_relation = input('urgent_relation');
            $urgent_mobile = input('urgent_mobile');
            $work_experience = input('work_experience');
            $bank_cardnum = input('bank_cardnum');
            $bankName = input('bankName');
            $company_id = input('company_id/d', 0);

            if (empty($name)) {
                $this->no('请输入姓名');
            }
            if (empty($gender)) {
                $this->no('请选择性别');
            }
            if (empty($idcard)) {
                $this->no('请输入身份证号');
            }
            if (!checkIdCard($idcard)) {
                $this->no('身份证号不合法');
            }
            if (empty($currentAddress)) {
                $this->no('请输入现住址');
            }
            if (empty($permanentAddress)) {
                $this->no('请输入户籍地址');
            }
            if (empty($urgent_name)) {
                $this->no('请输入紧急联系人姓名');
            }

            if (empty($urgent_relation)) {
                $this->no('请输入与紧急联系人关系');
            }

            if (empty($urgent_mobile)) {
                $this->no('请输入紧急联系人电话');
            }

            if (!preg_match("/^1\d{10}$/", $urgent_mobile)) {
                $this->no('紧急联系人电话格式错误');
            }

            if (empty($work_experience)) {
                $this->no('请填写工作经历');
            }

            if (empty($bank_cardnum)) {
                $this->no('请输入银行卡号');
            }

            if (empty($bankName)) {
                $this->no('请输入开户行名称');
            }

            if (empty($company_id)) {
                $this->no('请选择入职公司');
            }

            $exists = Staff::where(['idcard'=>$idcard, 'id'=>['<>', $uid]])->find();
            if (!empty($exists)) {
                $this->no('您输入的身份证号码已被绑定');
            }

            $data = [
                'name'=>$name,
                'gender'=>$gender,
                'idcard'=>$idcard,
                'currentAddress'=>$currentAddress,
                'permanentAddress'=>$permanentAddress,
                'urgent_name'=>$urgent_name,
                'urgent_relation'=>$urgent_relation,
                'urgent_mobile'=>$urgent_mobile,
                'work_experience'=>$work_experience,
                'bank_cardnum'=>$bank_cardnum,
                'bankName'=>$bankName,
                'company_id'=>$company_id,
            ];
            $res = $staffInfo->save($data);
            if (empty($res)) {
                $this->no('保存失败');
            }

            $this->yes('提交成功');
        }

        $companyList = Company::order('weigh', 'desc')->select();

        $this->view->assign('staffInfo', $staffInfo);
        $this->view->assign('companyList', $companyList);
        return $this->view->fetch();
    }

    // 查询用户信息
    public function lookuserinfo()
    {
        $uid = session('salary_uid');
        if (empty($uid)) {
            header('location:' . url('index/index'));
            exit();
        }

        $staffInfo = Staff::where('id', $uid)->find();
        if (empty($staffInfo)) {
            header('location:' . url('index/register'));
            exit();
        }

        $companyInfo = Company::where('id', $staffInfo['company_id'])->find();

        $this->view->assign('staffInfo', $staffInfo);
        $this->view->assign('companyInfo', $companyInfo);
        return $this->view->fetch();
    }

    // 阿里云发送验证码
    public function sendcode_aliyun() {
        $telMsgCookie = session('telMsgCookie');
        if (!empty($telMsgCookie) && (time()-$telMsgCookie <= 60)) {
            $this->no('请稍后再试');
        }

        $mobile = input('mobile');
        if (empty($mobile)) {
            $this->no('手机号码不能为空');
        }

        if (!preg_match("/^1[2|3|4|5|6|7|8|9]\d{9}$/", $mobile)) {
            $this->no('手机号码格式不正确');
        }

        $code = rand(100000, 999999);

        // 记录
        $insertData = array(
            'mobile'=>$mobile,
            'code'=>$code,
            'status'=>1,
            'dateline'=>date('Y-m-d H:i:s'),
        );

        // 设置 60秒 COOKIE  防止恶意刷
        session('telMsgCookie', time());

        // 阿里云发送短信
        try {

            $params = ['code' => $code];

            $smsService = new AliSmsService();
            $response = $smsService->sendSms($mobile, $params);
            $insertData['result'] = serialize($response);

            if ($response['Message'] == 'OK' && $response['Code'] == 'OK') {
                Msglog::insert($insertData);

                session('mobile_code', array('mobile'=>$mobile, 'code'=>$code));

                $this->yes('发送成功');
            } else {
                $insertData['status'] = 0;
                Msglog::insert($insertData);

                $this->no('短信发送失败了,'.$response['Message'], $response);
            }
        } catch (\think\Exception $e) {
            $insertData['status'] = 0;
            $insertData['result'] = $e->getMessage();
            Msglog::insert($insertData);

            $this->no('短信发送失败,'.$e->getMessage(), $e->getMessage());
        }
    }

    // 凌凯发送验证码
    public function sendcode() {
        $telMsgCookie = session('telMsgCookie');
        if (!empty($telMsgCookie) && (time()-$telMsgCookie <= 60)) {
            $this->no('请稍后再试');
        }

        $mobile = input('mobile');
        if (empty($mobile)) {
            $this->no('手机号码不能为空');
        }

        if (!preg_match("/^1[2|3|4|5|6|7|8|9]\d{9}$/", $mobile)) {
            $this->no('手机号码格式不正确');
        }

        // ceshi
        // $name = '章三';
        // // $content = '尊敬的家长，您好！今日有'.$name.'同学的值日安排，需要您安排时间值日，详情请查看群消息，感谢！';
        // // $content = '尊敬的家长，您好！三天后有'.$name.'同学的值日安排，需要您安排时间值日，详情请查看群消息，感谢！';
        // $content = '尊敬的家长，您好！明日有'.$name.'同学的值日安排，需要您安排时间值日，详情请查看群消息，感谢！';
        // $res = $this->lingkai_sms_other($mobile,$content);
        // var_dump($res);die;

        $code = rand(100000, 999999);

        // 记录
        $insertData = array(
            'mobile'=>$mobile,
            'code'=>$code,
            'status'=>1,
            'dateline'=>date('Y-m-d H:i:s'),
        );

        // 设置 60秒 COOKIE  防止恶意刷
        session('telMsgCookie', time());

        // 凌凯发送短信
        $response = $this->lingkai_sms($mobile,$code);
        $insertData['result'] = serialize($response);

        if ($response['code'] == 0) {
            Msglog::insert($insertData);

            // 设置 60秒 COOKIE  防止恶意刷
            session('mobile_code', array('mobile'=>$mobile, 'code'=>$code));

            $this->yes('发送成功');
        } else {
            $insertData['status'] = 0;
            Msglog::insert($insertData);

            $this->no('短信发送失败了,'.$response['msg'], $response);
        }
    }

    /*凌凯发送短信*/
    public function lingkai_sms($mobile,$code){
        $url = "https://api.028lk.com/Sms/Api/Send";
        $data = array(
            "SecretName" =>'GZZXY00007544',
            "SecretKey" => 'xawhxx@52017zy',
            "Mobile" => $mobile,
            "Content" => '您的验证码：'.$code.'，您正在进行身份验证，请勿泄露于他人！',
            "TemplateId" => '',
            "ExtCode" => '',
            "SignName" => '【西安五禾】',
            "Timing" => '',
            "CustomId" => '',
        );
        $postData=json_encode($data);
        $postHeader=array(
            "Content-Type: application/json; charset=utf-8",
            "Content-Length:".strlen($postData)
        );
        //POST方式请求
        $curl = curl_init();
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,$postHeader);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $result = curl_exec($curl);
        curl_close($curl);

        // echo("<br>");
        // echo('<table class="XS"><tr><td>');
        // echo("请求地址：".$url);
        // echo('<br>');
        // echo("接口返回值为：<br>");
        // echo($result);
        // echo('</td></tr></table>');

        return json_decode($result, true);


    }

    /*凌凯发送短信其它模版*/
    public function lingkai_sms_other($mobile,$content){
        $url = "https://api.028lk.com/Sms/Api/Send";
        $data = array(
            "SecretName" =>'GZZXY00007544',
            "SecretKey" => 'xawhxx@52017zy',
            "Mobile" => $mobile,
            "Content" => $content,
            "TemplateId" => '',
            "ExtCode" => '',
            "SignName" => '【西安五禾】',
            "Timing" => '',
            "CustomId" => '',
        );
        $postData=json_encode($data);
        $postHeader=array(
            "Content-Type: application/json; charset=utf-8",
            "Content-Length:".strlen($postData)
        );
        //POST方式请求
        $curl = curl_init();
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,$postHeader);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $result = curl_exec($curl);
        curl_close($curl);

        // echo("<br>");
        // echo('<table class="XS"><tr><td>');
        // echo("请求地址：".$url);
        // echo('<br>');
        // echo("接口返回值为：<br>");
        // echo($result);
        // echo('</td></tr></table>');

        return json_decode($result, true);


    }

    public function encrypt($data,$key = 'fxzdfs2343') {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0,$iv);
        return base64_encode($iv .$encrypted); // 将IV和加密后的数据一起编码
    }

    public function decrypt($data,$key = 'fxzdfs2343') {
        $data = base64_decode($data);
        $iv = substr($data, 0, openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = substr($data, openssl_cipher_iv_length('aes-256-cbc'));
        return openssl_decrypt($encrypted, 'aes-256-cbc',$key, 0, $iv);
    }

}
